﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace IFramework
{
    /// 校验相关的实用函数。
    public class Verifier
    {
        private static readonly byte[] Zero = new byte[] { 0, 0, 0, 0 };

        /// 计算二进制流的 CRC32。
        public static byte[] GetCrc32(byte[] bytes)
        {
            if (bytes == null)
            {
                return Zero;
            }
            using (MemoryStream memoryStream = new MemoryStream(bytes))
            {
                Crc32 calculator = new Crc32();
                byte[] result = calculator.ComputeHash(memoryStream);
                calculator.Clear();
                return result;
            }
        }

        /// 计算指定文件的 CRC32。
        public static byte[] GetCrc32(string fileName)
        {
            if (!File.Exists(fileName))
            {
                return Zero;
            }
            using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                Crc32 calculator = new Crc32();
                byte[] result = calculator.ComputeHash(fileStream);
                calculator.Clear();
                return result;
            }
        }

        /// 计算二进制流的 MD5。
        public static string GetMD5(byte[] bytes)
        {
            MD5 alg = new MD5CryptoServiceProvider();
            byte[] data = alg.ComputeHash(bytes);
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                stringBuilder.Append(data[i].ToString("x2"));
            }
            return stringBuilder.ToString();
        }
        public static string GetFileMD5(string absPath)
        {
            if (!File.Exists(absPath))
                return "";

            MD5CryptoServiceProvider md5CSP = new MD5CryptoServiceProvider();
            FileStream file = new FileStream(absPath, FileMode.Open);
            byte[] retVal = md5CSP.ComputeHash(file);
            file.Close();
            string result = "";

            for (int i = 0; i < retVal.Length; i++)
            {
                result += retVal[i].ToString("x2");
            }

            return result;
        }
        public static string GetStrMD5(string str)
        {
            MD5CryptoServiceProvider md5CSP = new MD5CryptoServiceProvider();
            byte[] retVal = md5CSP.ComputeHash(Encoding.Default.GetBytes(str));
            string retStr = "";

            for (int i = 0; i < retVal.Length; i++)
            {
                retStr += retVal[i].ToString("x2");
            }

            return retStr;
        }
    }
  
}
